package com.boot.security.service.authentication;

import com.boot.database.service.CurrentUserHandler;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

/**
 * @author 霜寒 <1621856595@qq.com>
 * @date 2020/2/14 22:02
 **/
@Primary
@Repository
public class CurrentUserUtil implements CurrentUserHandler {

    @Override
    public void setUsername(String username) {

    }

    @Override
    public String getUsername() {
        try {
            String username = SecurityContextHolder.getContext().getAuthentication().getName();
            if (StringUtils.hasText(username)) {
                return username;
            }
            return "system";
        } catch (NullPointerException ignore) {
            return "system";
        }
    }

}
